package org.kzwl.service.app.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.kzwl.comm.pojo.bo.category.CategoryBasic;
import org.kzwl.comm.pojo.bo.comment.AddCommentBO;
import org.kzwl.comm.pojo.bo.comment.QueryCommentBO;
import org.kzwl.comm.pojo.dto.comment.CommentDTO;
import org.kzwl.entity.app.Agree;
import org.kzwl.entity.app.Comment;
import org.kzwl.mapper.app.AgreeMapper;
import org.kzwl.mapper.app.CommentMapper;
import org.kzwl.service.app.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-09-10
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private AgreeMapper agreeMapper;

    //region 添加评论
    @Override
    public void addComment(AddCommentBO bo) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(bo, comment);
        commentMapper.insert(comment);
    }
    //endregion

    //region 查询评论
    @Override
    public List<CommentDTO> queryComment(QueryCommentBO bo) {
        bo.setCurrent((bo.getCurrent() - 1) * bo.getSize());
        List<CommentDTO> commentDTOS = commentMapper.queryComment(bo);
        commentDTOS.forEach(c -> {
            QueryWrapper<Agree> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Agree::getCuAgreeExt, c.getCuCommentId());
            Integer integer = agreeMapper.selectCount(queryWrapper);
            c.setCuAgreeNumber(integer);
            queryWrapper.lambda().eq(Agree::getCuUserId, bo.getCuUserId());
            integer = agreeMapper.selectCount(queryWrapper);
            if (integer > 0) {
                c.setIsAgree(1);
            }
        });
        CommentDTO basicComments = new CommentDTO();
        basicComments.setCuCommentId(0);
        foreach(basicComments, commentDTOS);
        return basicComments.getList();
    }
    //endregion

    private void foreach(CommentDTO main, List<CommentDTO> list) {
        for (CommentDTO menuDTO : list) {
            if (main.getCuCommentId().longValue() == menuDTO.getCuCommentParent().longValue()) {
                foreach(menuDTO, list);
                main.getList().add(menuDTO);
                CollectionUtil.sort(main.getList(), Comparator.comparingInt(CommentDTO::getCuCommentParent));
            }
        }
    }
}
